package com.example.dingdong.rest;

import java.util.HashMap;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.example.dingdong.daomain.MenuEntity;
import com.example.dingdong.daomain.OrderRecordEntity;
import com.example.dingdong.service.MenuService;
import com.example.dingdong.service.OrderService;
import com.example.dingdong.util.CheckRequestUtil;
import com.example.dingdong.util.ExceptionType;
import com.example.dingdong.util.MyException;

/**
 * 
 * @ClassName: PayRest
 * @Description: 
 * @Author :chengwenixng
 * @Copyright: Smartlab411
 * @DateTime 2022-03-27 00:39:10
 */
@RestController
@RequestMapping("web/rest/pay/")
public class PayRest {
	//创建日志
	private static final Logger log = LoggerFactory.getLogger(PayRest.class);
	@Autowired
	MenuService menuService;
	@Autowired
	private OrderService  orderService;
	
	public String APP_PRIVATE_KEY = "MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCgnpY6DQE+5Lebwrd+qsX33JhdxwJWtTh5oIWe3sIcS5u7ioKPg7m0T6NsdPiSRZoMtInI5plDtRq2WRuTs19/SLSy1F8WF279MsYmJR/2jdvmh+woB8JIQc8z621HwHnUEKItHMqlNfslGMjbSD1R9q7aXv+Ak9JY3BNYTw33Qv9VuXTThw75ao0TB51hnNgebam3szWLXCiRy7DFMVpWyZLXtIyeKWRi+n5YttVarmx7w0Nus9HvD1kakzxYsv7ks9okerFnRb+fPzgV+6lY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1zcfz0jImRfX4a3ziyJH6TirzhEUwpTYMgJvZoAP2FUUCgYBcTKcIkmIetzWZw+KoOgcAC1T11NMKI+Y9TMcmjUMvUGHGwDgtR0SISVg5csEvQG3M80DhUk0vmpZkHon9VxruodUhrlvAExn4YebZoDb5nZHumZd4dgNYkwTXAWQ5t5ahMIkbnntoapUj4fFW7NJ+V8EOYFAo4OttSCUE6HlhIQ==";
	public String alipay_public_key = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAidQzKn0c0/luJBhyD6v7uRIj2jeGV+Cea0qmmF4Ps9kiA2LQ2U7OqU2+KDgf06fg7wfAGRKPmM8Vt6QOGTmmy6bq/NBwWTLTEn906rx/olKHBil38wIhrsE4RF3XBXmyQYND8WRja5jZKzkskkflimJdJVIcgBm7PdTNlY6WaqzgR2KqTfoSAs/NS7j0Zg6y6INoK+h9PLIB2VodMTPj0CiH6gVEpdZ9Bj5HGpnnMFGc4ogpltc1SeXYlMJ2ZYU1e6c7Vl3ZhWglcL6wq0KugFMKGR6J1QqLS8KEnHIaza3QCZaNZK9uDpt6U/o5FA4HxMW4xV3qnajX5QCrqsRLoQIDAQAB";
	private AlipayTradePrecreateResponse precreateResponse;

	private AlipayClient alipayClient;

	
	@RequestMapping("alipay")
	public JSONObject alipay(@RequestBody String reqStr) {
		log.info("alipay:" + reqStr);
		/**
		 * 预返回数据
		 */
		JSONObject return_data = new JSONObject();
		JSONObject response = new JSONObject();
		return_data.put("cmd", "alipay");
		return_data.put("type", "response");
		return_data.put("response", response);

		try {
			JSONObject req = CheckRequestUtil.checkReqInterface(reqStr, "alipay");
			
			JSONArray data = new JSONArray();
			
			List<Object> idList =req.getJSONArray("idList");
			if (idList == null || idList.size() == 0) {
				throw new MyException(ExceptionType.NotFound, "请传入idList！");
			}
			
			/**
			 * 查找数据库中的数据
			 */
			for (Object object : idList) {
				 MenuEntity menuEntity =menuService.getMenuEntities(Long.valueOf(String.valueOf(object)).longValue(), true);
				if  ( menuEntity == null) {
					throw new MyException(ExceptionType.LookupDatabaseIsEmpty, "数据库中暂无该数据！");
				}
				//获取菜品价格
				double totalPrice=menuEntity.getPrice();
				 //获取订单号，当前时间戳
		        String out_trade_no = String.valueOf("2022"+"订单"+System.currentTimeMillis());
		        
		        //设置初始化的AlipayClient
		        alipayClient = new DefaultAlipayClient("https://openapi.alipaydev.com/gateway.do", "2021000116675376", APP_PRIVATE_KEY, "json", "utf-8", alipay_public_key, "RSA2");

		        AlipayTradePrecreateRequest precreateRequest = new AlipayTradePrecreateRequest();
		        JSONObject addData = new JSONObject();
				addData.put("out_trade_no",out_trade_no); // 订单号
				addData.put("total_amount",totalPrice); // 支付金额
				addData.put("subject",menuEntity.getId()); // 商品id
				addData.put("timeout_express","90m");//该笔订单允许的最晚付款时间，预期将关闭交易
				addData.put("scene","bar_code"); // 商品名称
		        precreateRequest.setBizContent(JSON.toJSONString(addData));
		        precreateRequest.setReturnUrl("success");
		        String body = alipayClient.pageExecute(precreateRequest).getBody();
		        System.out.println(body);

		        precreateResponse = alipayClient.execute(precreateRequest);
	            if (precreateResponse.isSuccess()) {
	                System.out.println("调用成功");
	            }
	            //获取二维码链接
	            addData.put("qrcode", precreateResponse.getQrCode());
	            OrderRecordEntity orderRecordEntity=new  OrderRecordEntity();
	            orderRecordEntity.setTotalPrice(totalPrice);
	            orderRecordEntity.setOriderNumber(out_trade_no);
	            orderRecordEntity.setMenuEntity(menuEntity);
	            orderRecordEntity.getBasicUserEntity().setAddress(menuEntity.getBasicUserEntity().getAddress());
	            orderRecordEntity.getBasicUserEntity().setPhone(menuEntity.getBasicUserEntity().getPhone());
	            orderService.savaOrderEntities(orderRecordEntity);
			}
			
			/**
			 * 返回前端数据
			 */
			response.put("res", true);
//			response.put("message",  addData);
		} catch (MyException e) {
			log.error("alipay:" + e.getReason());
			response.put("res", false);
			response.put("exception", e.getReason());
		} catch (Exception e) {
			log.error("alipay:" + e.getMessage());
			response.put("res", false);
			response.put("exception", e.getMessage());
		}
		return return_data;
	}
	/**
	 * 查询支付状态
	 * @Title: queryStart
	 * @Description: 
	 * @Author coding
	 * @DateTime 2021-05-26 10:30:01
	 * @param reqStr
	 * @return
	 */
	@RequestMapping("query")
	public JSONObject queryStart(@RequestBody String reqStr) {
		log.info("query:" + reqStr);
		/**
		 * 预返回数据
		 */
		JSONObject return_data = new JSONObject();
		JSONObject response = new JSONObject();
		return_data.put("cmd", "query");
		return_data.put("type", "response");
		return_data.put("response", response);

		try {
			JSONObject req = CheckRequestUtil.checkReqInterface(reqStr, "query");
			/**
			 * 获取前端数据
			 */
			if (req.get("out_trade_no") == null) {
				throw new MyException("缺少out_trade_no字段！");
			}
			String out_trade_no = req.getString("out_trade_no");
			JSONObject addData = new JSONObject();
			AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
            HashMap hashMap = new HashMap();
            hashMap.put("out_trade_no", out_trade_no);
            request.setBizContent(JSON.toJSONString(hashMap));
            AlipayTradeQueryResponse response1 = null;
            try {
                response1 = alipayClient.execute(request);
            } catch (AlipayApiException e) {
                e.printStackTrace();
            }
            String code = response1.getCode();
            addData.put("status", response1.getTradeStatus());
			/**
			 * 返回前端数据
			 */
            response.put("messgae",addData);
			response.put("res", true);
		} catch (MyException e) {
			log.error("query:" + e.getReason());
			response.put("res", false);
			response.put("exception", e.getReason());
		} catch (Exception e) {
			log.error("query:" + e.getMessage());
			response.put("res", false);
			response.put("exception", e.getMessage());
		}
		return return_data;
	}
	
}
